package com.neighbor.spring.mysql;


import com.alibaba.druid.pool.DruidDataSource;
import com.neighbor.spring.core.SpringApplicationContext;
import com.neighbor.spring.mysql.operation.Delete;
import com.neighbor.spring.mysql.operation.Insert;
import com.neighbor.spring.mysql.operation.Query;
import com.neighbor.spring.mysql.operation.Update;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;

/**
 * @author ysw
 * @create 2019-04-22 15:08
 * @descreption
 **/
public class JdbcOperation {


    private DruidDataSource defaultDataSource;

    private String tableName;


    public JdbcOperation(DruidDataSource dataSource) {
        this.defaultDataSource = dataSource;
    }

    public JdbcOperation(DruidDataSource dataSource, String tableName) {
        this.defaultDataSource = dataSource;
        this.tableName = tableName;
    }


    public Jdbc2Template SQL() {
        return new Jdbc2Template(this.defaultDataSource);
    }

    //==========================
    public Long insert(Object object) {
        return Insert.insert(this.defaultDataSource, object, this.tableName);
    }


    public int[] insertBatch(List list) {
        return Insert.insertBatch(this.defaultDataSource, list, this.tableName);
    }

    public Query query(Class clazz, String... columns) {
        DruidDataSource dataSource = defaultDataSource;
        DataSourceList dataSourceList = SpringApplicationContext.getBean("dataSourceList");
        if(dataSourceList != null && !CollectionUtils.isEmpty(dataSourceList.getList())){
            Random random = new Random();
            int i = random.nextInt(dataSourceList.getList().size());
            dataSource = dataSourceList.getList().get(i);
        }
        return Query.query(clazz, this.tableName, dataSource, columns);
    }

    public Delete delete(Class clazz) {
        return Delete.delete(clazz, this.tableName, this.defaultDataSource);
    }

    public Update update(Class clazz) {
        return Update.update(clazz, this.tableName, this.defaultDataSource);
    }


}
